import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { RestService } from '../../services/rest.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-alarm-dialog',
  templateUrl: './alarm-dialog.component.html',
  styleUrls: ['./alarm-dialog.component.css']
})
export class AlarmDialogComponent implements OnInit {
  contentHeight = '65vh';
  person: any;
  alarm = '';
  url = 'data/alarm/search/findAlarmTypeAfter';
  institution: any;
  displayedColumns: string[] = ['number', 'raisedTime', 'type', 'ackedTime', 'personName', 'deviceId'];
  dataSource = [];
  searchText = '';
  isLoadingResults = true;

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<AlarmDialogComponent>,
              private translate: TranslateService,
              private rest: RestService,
              private dialog: MatDialog) {
    this.person = dialogData.person;
    this.alarm = dialogData.alarm;
    this.institution = this.rest.getInstitution();

    if (this.alarm === 'MOVE') {
      this.displayedColumns = ['number', 'time', 'value'];
    }
  }

  getTitle() {
    if (this.alarm === 'MOVE') {
      return this.person.personName + ' - ' + this.translate.get('move')['value'];
    } else {
      return this.person.personName + ' - ' + this.translate.get(this.alarm)['value'];
    }
  }

  getTimeFromLast8Am() {
    let hour = new Date().getHours();
    hour = hour >= 8 ? (hour - 8) : (24 + hour - 8);
    const seconds = hour * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds() - 1;
    const result = new Date().getTime() - 1000 * seconds;
    return result;
  }

  ngOnInit() {
    if (this.alarm === 'MOVE') {
      this.rest.getWithParams('/data/moves', {
        personId: this.person.id,
        from: this.getTimeFromLast8Am()
      }).subscribe(resp => {
        this.isLoadingResults = false;
        const moves = [];
        if (resp instanceof Array) {
          resp.forEach((item, index) => {
            moves.push({
              'number': index + 1,
              'time': item,
              'value': 1
            });
          });
        }
        this.dataSource = moves;
      }, message => {
        this.isLoadingResults = false;
      });

      return;
    }

    this.rest.getWithParams(this.url, {
      institutionId: this.institution.id,
      personId: this.person.id,
      alarm: this.rest.getAlarmEnumNumber(this.alarm),
      from: this.getTimeFromLast8Am()
    }).subscribe(resp => {
      this.isLoadingResults = false;
      let number = 1;
      const alarms = resp['_embedded']['alarms'];
      alarms.forEach(alarm => {
        alarm['number'] = number++;
      });
      this.dataSource = alarms;
    }, message => {
      this.isLoadingResults = false;
    });
  }
}
